import routes from '../route/route'
import sessionHandle from './sessionHandle'
const jwt = require('jsonwebtoken');
import '../adminRoute/adminRoute'
import mongodbHandle from './mongodbHandle';


let lodash = require("lodash")

let verificationtype = {
    string: 'isString',
    number: 'isNumber',
    boolean: 'isBoolean',
    null: 'isNull',
    object: 'isObject',
    array: 'isArray'
}

function verification(msg, arr) {
    for (let item of arr) {
        let key = item[0];
        let type = item[1];
        let require = item[2];
        let value = msg[key];
        if ((value == undefined || value == null) && require == false) {
            return
        }
        //类型验证 string ,number, boolean, null, object, array
        if (lodash[verificationtype[type]](value) == false) {
            return key;
        }
        if (type === 'number') {
            if (!Number.isInteger(value)) { //必须是整形
                return key;
            }
        }
    }
    return
}

let routeHandle = async (url, msg, token) => {

    let validationData = routes.validationData[url];
    if (validationData) {
        let ret = verification(msg, validationData);
        if (ret) {
            return {
                err: 104,
                data: ret,
                code: 0
            }
        }
    }

    let notUserLoginRoute = routes.userNotLogin[url];
    if (notUserLoginRoute) {
        let { err, data, code } = await notUserLoginRoute(msg);
        return {
            err: err,
            data: data,
            code: code || 0
        }
    }

    let notLoginRoute = routes.notLogin[url];
    if (notLoginRoute && token) {
        let { err, data, code } = await notLoginRoute(msg, token)
        return {
            err: err,
            data: data,
            code: code || 0
        }
    }

    let loginRoute = routes.login[url];
    if (loginRoute && token) {
        let { err, data, code } = await loginRoute(msg, token)
        if(err == 0){
            mongodbHandle.adminRecordDao.newAndSave(token.name, url, JSON.stringify(msg))
        }
        return {
            err: err,
            data: data,
            code: code || 0
        };
    }

    return {
        err: 103,
        data: url
    };

}


export default routeHandle